package com.ztf0337.mycurriculumdesign.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.Utils.AccountUtils;
import com.ztf0337.mycurriculumdesign.Utils.TextDate;
import com.ztf0337.mycurriculumdesign.Utils.TimeConverters;
import com.ztf0337.mycurriculumdesign.Utils.TransitionUtils;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.RentedParkingSpace;
import com.ztf0337.mycurriculumdesign.service.OrderService;
import com.ztf0337.mycurriculumdesign.service.ParkLotService;
import com.ztf0337.mycurriculumdesign.service.ParkingSpaceService;
import com.ztf0337.mycurriculumdesign.service.RentService;

public class SettleAccountsActivity extends AppCompatActivity {

    Long Uid;
    Boolean login;
    private Runnable timerRunnable;

    private TextView tvNumber,tvParkLotName,tvPrice,tvLocation,tvType,tvStartTime,tvTotalTime,tvEndTime,tvLicencePlate;
    private Button btnCancel,btnOrder;
    private Handler handler = new Handler();
    private OrderService orderService;
    private ParkingSpaceService parkingSpaceService;
    private RentService rentService;
    private ParkLotService parkLotService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settle_accounts);
        orderService = new OrderService(this);
        parkingSpaceService = new ParkingSpaceService(this);
        rentService = new RentService(this);
        parkingSpaceService = new ParkingSpaceService(this);
        parkLotService = new ParkLotService(this);

        Intent intent = getIntent();
        Long id = intent.getLongExtra("id", -1L);


        Log.d("测试","租借接受id "+id);
        if (id.equals(-1L)) {
            Toast.makeText(this, "系统错误", Toast.LENGTH_SHORT).show();
            finish();
        }

        RentedParkingSpace rentById = rentService.getRentById(id);
        Order order = orderService.getOrderById(rentById.getOrderId());
        ParkingSpace parkingSpaceById = parkingSpaceService.getParkingSpaceById(order.getParkingSpaceId());

        tvNumber = findViewById(R.id.tvNumber);
        tvNumber.setText(order.getParkingSpaceNumber());

        tvParkLotName = findViewById(R.id.tvParkLotName);
        tvParkLotName.setText(order.getParkLotName());

        tvType = findViewById(R.id.tvType);
        tvType.setText(TransitionUtils.transParkType(order.getParkType()));

        tvLocation = findViewById(R.id.tvLocation);
        tvLocation.setText(order.getLocation());

        tvStartTime = findViewById(R.id.tvStartTime);
        tvStartTime.setText(TimeConverters.format(order.getStartTime()));


        tvLicencePlate = findViewById(R.id.tvLicencePlate);
        tvLicencePlate.setText(order.getLicencePlate());


        btnCancel = findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(v -> {
            finish();
        });
        //结算
        btnOrder = findViewById(R.id.btnOrder);
        btnOrder.setOnClickListener(v -> {
            payment(order,parkingSpaceById,rentById);
        });

        timerRunnable = new Runnable() {
            @Override
            public void run() {
                long now = System.currentTimeMillis();
                Long startTime = order.getStartTime();

                tvPrice = findViewById(R.id.tvPrice);
                tvEndTime = findViewById(R.id.tvEndTime);
                tvTotalTime = findViewById(R.id.tvTotalTime);

                double t = TimeConverters.calculateHours(startTime, now);
                tvPrice.setText(AccountUtils.settleAccountToString(parkingSpaceById.getPricePerHours() ,t));
                tvEndTime.setText(TimeConverters.format(now));
                tvTotalTime.setText(t +" 小时");
                handler.postDelayed(this, 1000);
            }
        };
        handler.post(timerRunnable); // 启动计时

    }

    private void payment(Order order,ParkingSpace parkingSpace, RentedParkingSpace rentedParkingSpace) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_payment, null);

        order.setEndTime(TimeConverters.getNewTime());
        order.setTotalPrice(AccountUtils.settleAccountToDouble(parkingSpace.getPricePerHours(), TimeConverters.calculateHours(order.getStartTime(),order.getEndTime())));
        order.setTransactionStatus(true);
        order.setTotalTime(TimeConverters.calculateHours(order.getStartTime(), order.getEndTime()));
        orderService.update(order);
        rentService.delete(rentedParkingSpace);
        parkingSpace.setStatus(true);
        parkingSpaceService.update(parkingSpace);

        ParkLot parkLotById = parkLotService.getParkLotById(parkingSpace.getParkLotId());
        parkLotById.setAvailableSpaces(parkLotById.getAvailableSpaces()+1);
        parkLotService.update(parkLotById);
        Log.d("测试","结算成功");

        AlertDialog loadingDialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(false)
                .create();

        loadingDialog.show();

        // 1 秒后关闭 Dialog
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            loadingDialog.dismiss();
            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("open",2);
            startActivity(intent);
            finish();
        }, 1000);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(timerRunnable); // 防止内存泄漏
    }

}
